import { LoginService } from '@service/login.service';
/* 配置路由守卫 */
import { AuthService } from '@service/auth.service';
import { Injectable } from '@angular/core';
import { CanActivateChild, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message/';
import { CookieService } from '@core/net/cookie';
import { Observable } from 'rxjs';
import { MenuService } from '@service/menu.service';

@Injectable({
	providedIn: 'root'
})
export class AuthGuard implements CanActivateChild {

	constructor(
		private authService: AuthService,
		private router: Router,
		private messageServ: NzMessageService,
		private cookieService: CookieService,
		private loginService: LoginService,
		private menuService: MenuService
	) { }

	canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
		const url: string = state.url;
		return this.checkLogin(url);
	}

	canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
		const url: string = state.url;
		const menu = this.menuService.isLoadMenu(url);
		// console.log(menu);
		if (!menu) {
			this.router.navigateByUrl('/exception/403');
			return false;
		}
		return this.canActivate(route, state);
	}
	checkLogin(url): Observable<boolean> | Promise<boolean> | boolean {
		// const _authServ = this.authService;
		const _router = this.router;
		const cookieToken = this.cookieService.get('LtpaToken');
		const userInfo = this.loginService.getUserInfo();
		if (userInfo?.token) {
			return true;
		} else {
			if (cookieToken) {
				userInfo.token = cookieToken;
				userInfo.isSSo = true;
				return new Promise(async (resolve, reject) => {
					const result = await this.loginService.login({
						token: cookieToken
					});
					if (result.success) {
						const auth = result.data;
						this.loginService.saveUserInfo({username: auth.userDisplayName, token: auth.Authorization,  usercode: auth.username});
						this.authService.saveAuth(auth?.user?.currentRoles);
						resolve(true);
					} else {
						_router.navigate(['/login'], { queryParams: { redirectUrl: url } });
						resolve(false);
					}
				}).then((result: boolean) => {
					return result;
				});
			} else {
				this.router.navigate(['/login'], { queryParams: { redirectUrl: url } });
				return false;
			}
		}
	}
}
